import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AdminLoginFrame extends JFrame {
    private JTextField accountField;
    private JPasswordField passwordField;

    public AdminLoginFrame() {
        setTitle("MBTI职业性格测试 - 管理员登录");
        setSize(400, 250); // 调整窗口大小以容纳注册按钮
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(3, 2)); // 增加一行用于注册按钮

        JLabel accountLabel = new JLabel("账号:");
        panel.add(accountLabel);

        accountField = new JTextField();
        panel.add(accountField);

        JLabel passwordLabel = new JLabel("密码:");
        panel.add(passwordLabel);

        passwordField = new JPasswordField();
        panel.add(passwordField);

        JButton loginButton = new JButton("登录");
        panel.add(loginButton);

        JButton registerButton = new JButton("注册"); // 添加注册按钮
        panel.add(registerButton);

        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    String account = accountField.getText().trim();
                    String password = new String(passwordField.getPassword()).trim();
                    UserDAO userDAO = new UserDAOImpl();
                    User user = userDAO.findByAccountAndPIN(account, password);
                    if (user != null && "manager".equals(user.getUtype())) {  // 验证是否是管理员类型的用户
                        ManagerDAO managerDAO = new ManagerDAOImpl();
                        Manager manager = managerDAO.findByAccount(account);
                        if (manager != null) {
                            JOptionPane.showMessageDialog(AdminLoginFrame.this, "登录成功！");
                            new AdminFrame().setVisible(true);
                            dispose();
                        } else {
                            JOptionPane.showMessageDialog(AdminLoginFrame.this, "管理员信息获取失败，请联系管理员！", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        JOptionPane.showMessageDialog(AdminLoginFrame.this, "账号或密码错误，或非管理员账号！", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(AdminLoginFrame.this, "登录出现未知错误，请稍后重试！", "错误", JOptionPane.ERROR_MESSAGE);
                    ex.printStackTrace();
                }
            }
        });

        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new AdminRegisterFrame().setVisible(true); // 点击注册按钮时弹出管理员注册界面
            }
        });

        add(panel);
    }
}